<?php

namespace app\admin\controller;

use think\Request;
use think\Db;
use think\Validate;

class Role extends AdminController
{
    public function index()
    {
        $list = Db::name('role')
                ->field(['id', 'remark', 'name', 'status'])
                ->select();
//        echo db('table')->getlastsql();
        return view('role/index', [
            'list' => $list
        ]);
    }

    public function add()
    {
        return view('admin@role/add');
    }

    public function doAdd(Request $request)
    {
        $data = input('post.');

        $result = Db::name('role')->insert($data);

        if ($result > 0) {
            return $this->success('添加成功!', '/admin/role/index');
        }else{
            return $this->error('添加失败!');
        }
    }

    public function nodelist($id)
    {
        // 判断是否传正确的值
        if (!preg_match("/^\d*$/", $id)) {
            return $this->success('404 NOT FOUND!', '/admin/User/index');
        }

        //查询节点信息
        $list = Db::name('node')->where(['status' => 1])->select();
        //查询当前角色信息
        $roles = Db::name('role')->where(['id' => $id])->find();
        //获取当前角色的权限信息
        $nodelist = Db::name('role_node')->where(['rid' => $id])->select();

        $mynode = array(); // 定义空数组

        //对用户的角色进行重组
        foreach ($nodelist as $v) {
            $mynode[] = $v['nid'];
        }

        // 渲染模板
        return view('Role/nodelist', [
            'list' => $list,
            'roles' => $roles,
            'mynode' => $mynode
        ]);
    }

    public function savenode(Request $request)
    {
        $p = input('post.');
//        var_dump($p);die;
        //判读必须选择一个角色
        if (empty($p['node'])) {
            $this->error("请选择一个角色！");
        }
        $rid = $p['rid'];
        // 判断是否存在当前角色
        $row = Db::name('role')->where(['id' => $rid])->find();
        if ($row == 0) {
            return $this->success('页面出错, 不要搞事情(╬◣д◢)', '/admin/Role/index');
        }

        //清除角色所有的权限信息，避免重复添加
        Db::name('role_node')->where(['rid' => $rid])->delete();

        foreach ($p['node'] as $v) {
            $data['rid'] = $rid;
            $data['nid'] = $v;
            //执行添加
            Db::name('role_node')->insert($data);
        }

        return $this->success('权限分配成功', '/admin/Role/index');
    }

}